/**
 *  @author  xiaody <xiaody09@163.com>
 *  @description  Editor enhancement module.
 */

;(function() {

'use strict';

var EditorPlus = {

	init : function() {
		'use strict';
		var editor = $( '#editor' );
		if ( editor.length === 0 )
			return false;
		if ( $( '#editortoolswitch', editor ).length )
			return;

		var toolbar = $( ".tb-editor-toolbar", editor );
		if ( toolbar.length ) {
			var miyu_span = $( '<span>' ).attr( {'class':'miyutool','data-cmd':'miyutool','title':'密语'} );
			miyu_span.click(EditorPlus.encodePost);

			var yycode_span = $( '<span>' ).attr( {'class':'yycodetool','data-cmd':'yycodetool','title':'UUcode'} );
			yycode_span.click(UUcode.codeInsert);

			var sw = $( '<span>' ).attr({
				id : 'editortoolswitch',
				title : '奇怪的工具们',
				onclick : '$(this).siblings(":not([id])").animate({width:"toggle",paddingLeft:"toggle",opacity:"toggle"},300)'
			}).text( '##' );

			miyu_span.text( '密语' );
			yycode_span.text( 'UUcode' );

			toolbar.append( sw, miyu_span, yycode_span );
		}

		$( 'form', editor ).focus( initUnicode, true );

		$.inject( injectFuc );
	},
	encodePost : function() {
		var editarea = $( ".tb-editor-editarea" );
		var pos = editarea.html();

		if ( !pos )
			return;
		if ( pos.substring(0,8) !== '#Base64#' && pos.substring(0,4) !== '百度密语' ) {
			EditorPlus.originPost = pos;
			editarea.html( Miyu.encode( EditorPlus.originPost ) );
			editarea.attr( 'contenteditable', false );
		} else if ( pos.substring(0,4) === '百度密语' ) {
			editarea.html( '#Base64#' + Base64.encode( EditorPlus.originPost ) );
			editarea.attr( 'contenteditable', false );
		} else if ( pos.substring(0,8) === '#Base64#' ) {
			editarea.html( EditorPlus.originPost );
			editarea.attr( 'contenteditable', true );
		}
	},
	originPost : ''

};

function initUnicode() {
	'use strict';
	if ( $( '#useUnicode' ).length )
		return;

	var mainTd = $( '#editor .editor_users' );
	if ( mainTd.length === 0 )
		return false;
	else
		mainTd = mainTd.parent();

	var useUnicode = $( '<input>' ).attr( { 'type': 'checkbox', 'id': 'useUnicode' } ),
		label = $( '<label>' ).attr( {'title': '繁体字、反和谐时用', 'for': 'useUnicode'} ).text( '使用Unicode发表' );
	if ( switchesStorage.getSwitch( 'useUnicode' ) )
		useUnicode.prop( 'checked' , true );
	useUnicode.click( switchesStorage.getSwitchFunc( 'useUnicode' ) );
	var div = $( '<div>' ).append( useUnicode ).append( label );

	// Wait a little bit to make it looks more like Tieba native.
	setTimeout( function(){ mainTd.append( div ); }, 33 );

	$('#editor form')[0].removeEventListener( 'focus', initUnicode );
}

var injectFuc = function() {
		/**
		 * @param {string} str
		 * @return {string}
		 * @nosideeffects
		 */
		function uni( str ) {
			'use strict';
			str = str.replace( /<br.*?>/g, '<br>' );
			var ret = '',
				f = [];
			for ( var i = 0, l = str.length; i < l; i++ ) {
				if ( /[<&]/.test( str[i] ) && f[f.length-1] === '@')
					f.pop();
				if ( /[<@&]/.test(str[i]) )
					f.push(str[i]);
				if ( f.length === 0 )
					ret += "&#" + str.charCodeAt(i) + ";";
				else
					ret += str[i];
				if ( str[i] === '>' && f[f.length-1] === '<' )
					f.pop();
				else if ( str[i] === ';' && f[f.length-1] === '&' )
					f.pop();
			}
			return ret;
		}

		/** @const */
		var freeze = Object.freeze;

		/**
		 * @return {!Object} the post content.
		 */
		RichPostor.prototype._getData = function() {
			'use strict';
			var C = this._data_postor,
				E = this._data_editor,
				B = this._dom_id;
			if ( this._option.title ) {
				var I = $( '#' + this._option.title );
				if ( I.length ) {
					C.title = I.val();
				}
			}
			var bLogIn = E.is_login,
				$sign = $( "#useSignName" ),
				$notAnony = $( '#' + B.post_login ),
				$signId = $( "#sign_id" ),
				$unicode = $( "#useUnicode" );

			if ( $unicode.length && $unicode.prop( 'checked' ) ) {
				TED.Editor.prototype.parseURL = jQuery.noop;
				freeze( TED.Editor.prototype );
			}

			if ( bLogIn && $sign.length && $sign.prop( 'checked' ) && $signId.length )
				C.sign_id = $signId.val();
			if ( bLogIn && !$notAnony.prop( 'checked') )
				C.anonymous = 1;
			C.tbs = this._option.tbs;
			var G = this._captcha.getInputValue();
			if ( G != '' )
				C.vcode = G;
			C.vcode_md5 = this._captcha._option.sign_str;
			C.content = ( $unicode.length && $unicode.prop( 'checked' ) ) ? uni( this._editor.getHtml() ) : this._editor.getHtml();
			return C;
		};

		var config = TED.Editor.getInstanceById( 'tb-editor-1' ).getConfig();
		config.bavl = 18, config.picasso = true;

		freeze( RichPostor.prototype );
};

window.EditorPlus = EditorPlus;


})();
